<template>
  <div class="wms-merchant-balance-page art-full-height">
    <!-- 搜索栏 -->
    <WmsMerchantBalanceSearch
      v-model:filter="searchFilter"
      @search="handleSearch"
      @reset="handleReset"
    />

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格工具栏 -->
      <ArtTableHeader
        v-model:columns="columnChecks"
        @refresh="refreshData"
        layout="refresh,size,fullscreen,columns,settings"
      >
        <template #left>
          <ElButton type="primary" @click="showDialog('add')" v-ripple>
            <ElIcon><Plus /></ElIcon>
            新增余额记录
          </ElButton>
          <ElButton @click="showAdjustDialog" v-ripple>
            <ElIcon><Edit /></ElIcon>
            余额调整
          </ElButton>
          <ElButton @click="handleExport" v-ripple>
            <ElIcon><Download /></ElIcon>
            导出
          </ElButton>
          <ElButton @click="handleStatistics" v-ripple>
            <ElIcon><DataAnalysis /></ElIcon>
            统计分析
          </ElButton>
        </template>
      </ArtTableHeader>

      <!-- 数据表格 -->
      <ArtTable
        rowKey="id"
        :loading="isLoading"
        :data="tableData"
        :columns="columns"
        :pagination="paginationState"
        @selection-change="handleSelectionChange"
        @pagination:size-change="onPageSizeChange"
        @pagination:current-change="onCurrentPageChange"
      >
        <!-- 自定义列插槽 -->
        <template #merchantInfo="{ row }">
          <div class="merchant-info">
            <div class="merchant-name">{{ row.merchantName }}</div>
            <div class="merchant-code">{{ row.merchantCode }}</div>
          </div>
        </template>

        <template #balanceInfo="{ row }">
          <div class="balance-info">
            <div
              class="current-balance"
              :class="getBalanceClass(row.currentBalance)"
            >
              ¥{{ formatCurrency(row.currentBalance) }}
            </div>
            <div class="credit-limit" v-if="row.creditLimit">
              额度: ¥{{ formatCurrency(row.creditLimit) }}
            </div>
          </div>
        </template>

        <template #status="{ row }">
          <ElTag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? "正常" : "冻结" }}
          </ElTag>
        </template>

        <template #lastTransaction="{ row }">
          <div v-if="row.lastTransactionTime">
            {{ formatDate(row.lastTransactionTime) }}
          </div>
          <span v-else class="text-placeholder">-</span>
        </template>

        <template #actions="{ row }">
          <ElButton type="primary" link @click="showDialog('edit', row)">
            <ElIcon><Edit /></ElIcon>
            编辑
          </ElButton>
          <ElButton type="info" link @click="showDetailDialog(row)">
            <ElIcon><View /></ElIcon>
            余额明细
          </ElButton>
          <ElButton type="warning" link @click="showAdjustDialog(row)">
            <ElIcon><Money /></ElIcon>
            调整余额
          </ElButton>
          <ElButton type="danger" link @click="handleDelete(row)">
            <ElIcon><Delete /></ElIcon>
            删除
          </ElButton>
        </template>
      </ArtTable>
    </ElCard>

    <!-- 余额记录弹窗 -->
    <WmsMerchantBalanceDialog
      v-model:visible="dialogVisible"
      :type="dialogType"
      :balance-data="currentBalanceData"
      @submit="handleDialogSubmit"
    />

    <!-- 余额调整弹窗 -->
    <WmsMerchantBalanceAdjustDialog
      v-model:visible="adjustDialogVisible"
      :balance-data="currentBalanceData"
      @submit="handleAdjustSubmit"
    />

    <!-- 余额明细弹窗 -->
    <WmsMerchantBalanceDetailDialog
      v-model:visible="detailDialogVisible"
      :balance-data="currentBalanceData"
    />

    <!-- 统计分析弹窗 -->
    <WmsMerchantBalanceStatisticsDialog
      v-model:visible="statisticsDialogVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useTable } from "@/composables/useTable";
import { WmsMerchantBalanceService } from "@/api/wms/basicApi";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Edit,
  Delete,
  Download,
  View,
  Money,
  DataAnalysis,
} from "@element-plus/icons-vue";

// 导入子组件
import WmsMerchantBalanceSearch from "./components/WmsMerchantBalanceSearch.vue";
import WmsMerchantBalanceDialog from "./components/WmsMerchantBalanceDialog.vue";
import WmsMerchantBalanceAdjustDialog from "./components/WmsMerchantBalanceAdjustDialog.vue";
import WmsMerchantBalanceDetailDialog from "./components/WmsMerchantBalanceDetailDialog.vue";
import WmsMerchantBalanceStatisticsDialog from "./components/WmsMerchantBalanceStatisticsDialog.vue";

defineOptions({ name: "WmsMerchantBalance" });

// 表格配置和数据处理逻辑
const {
  tableData,
  columns,
  columnChecks,
  isLoading,
  paginationState,
  searchFilter,
  onPageSizeChange,
  onCurrentPageChange,
  refreshData,
  handleSearch,
  handleReset,
} = useTable<WMS.Basic.MerchantBalanceInfo>({
  core: {
    apiFn: WmsMerchantBalanceService.getMerchantBalanceList,
    apiParams: {
      current: 1,
      size: 20,
    },
    columnsFactory: () => [
      {
        type: "selection",
        width: 50,
      },
      {
        prop: "merchantInfo",
        label: "商户信息",
        slot: "merchantInfo",
        minWidth: 200,
        fixed: "left",
      },
      {
        prop: "balanceInfo",
        label: "余额信息",
        slot: "balanceInfo",
        width: 180,
        align: "center",
      },
      {
        prop: "status",
        label: "状态",
        slot: "status",
        width: 100,
        align: "center",
      },
      {
        prop: "lastTransaction",
        label: "最后交易时间",
        slot: "lastTransaction",
        width: 150,
        align: "center",
      },
      {
        prop: "createTime",
        label: "创建时间",
        width: 150,
        align: "center",
      },
      {
        prop: "remark",
        label: "备注",
        minWidth: 120,
        showOverflowTooltip: true,
      },
      {
        prop: "actions",
        label: "操作",
        slot: "actions",
        width: 250,
        fixed: "right",
        align: "center",
      },
    ],
  },
});

// 选中的行
const selectedRows = ref<WMS.Basic.MerchantBalanceInfo[]>([]);

// 弹窗状态管理
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const adjustDialogVisible = ref(false);
const detailDialogVisible = ref(false);
const statisticsDialogVisible = ref(false);
const currentBalanceData = ref<WMS.Basic.MerchantBalanceInfo | null>(null);

// 选择变化处理
const handleSelectionChange = (selection: WMS.Basic.MerchantBalanceInfo[]) => {
  selectedRows.value = selection;
};

// 获取余额样式类
const getBalanceClass = (balance: number) => {
  if (balance < 0) return "negative-balance";
  if (balance === 0) return "zero-balance";
  return "positive-balance";
};

// 格式化货币
const formatCurrency = (amount: number) => {
  return (
    amount?.toLocaleString("zh-CN", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }) || "0.00"
  );
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return "-";
  return new Date(dateString).toLocaleString("zh-CN");
};

// 显示余额记录弹窗
const showDialog = (
  type: "add" | "edit",
  data?: WMS.Basic.MerchantBalanceInfo,
) => {
  dialogType.value = type;
  currentBalanceData.value = data ? { ...data } : null;
  dialogVisible.value = true;
};

// 显示余额调整弹窗
const showAdjustDialog = (data?: WMS.Basic.MerchantBalanceInfo) => {
  currentBalanceData.value = data ? { ...data } : null;
  adjustDialogVisible.value = true;
};

// 显示余额明细弹窗
const showDetailDialog = (data: WMS.Basic.MerchantBalanceInfo) => {
  currentBalanceData.value = { ...data };
  detailDialogVisible.value = true;
};

// 显示统计分析弹窗
const handleStatistics = () => {
  statisticsDialogVisible.value = true;
};

// 余额记录弹窗提交处理
const handleDialogSubmit = async (data: WMS.Basic.MerchantBalanceInfo) => {
  try {
    if (dialogType.value === "add") {
      await WmsMerchantBalanceService.createMerchantBalance(data);
      ElMessage.success("新增余额记录成功");
    } else {
      await WmsMerchantBalanceService.updateMerchantBalance(data.id, data);
      ElMessage.success("更新余额记录成功");
    }
    dialogVisible.value = false;
    refreshData();
  } catch (error) {
    ElMessage.error(
      `${dialogType.value === "add" ? "新增" : "更新"}余额记录失败`,
    );
    console.error("Error submitting balance:", error);
  }
};

// 余额调整提交处理
const handleAdjustSubmit = async (data: any) => {
  try {
    await WmsMerchantBalanceService.updateMerchantBalanceAmount(data);
    ElMessage.success("余额调整成功");
    adjustDialogVisible.value = false;
    refreshData();
  } catch (error) {
    ElMessage.error("余额调整失败");
    console.error("Error adjusting balance:", error);
  }
};

// 删除处理
const handleDelete = async (row: WMS.Basic.MerchantBalanceInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商户 "${row.merchantName}" 的余额记录吗？`,
      "删除确认",
      { type: "warning" },
    );

    await WmsMerchantBalanceService.deleteMerchantBalance(row.id);
    ElMessage.success("删除余额记录成功");
    refreshData();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除余额记录失败");
      console.error("Error deleting balance:", error);
    }
  }
};

// 导出处理
const handleExport = () => {
  ElMessage.info("导出功能开发中");
};

// 页面初始化
onMounted(() => {
  refreshData();
});
</script>

<style lang="scss" scoped>
.wms-merchant-balance-page {
  .merchant-info {
    .merchant-name {
      font-weight: 500;
      color: var(--el-text-color-primary);
    }

    .merchant-code {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-top: 2px;
    }
  }

  .balance-info {
    .current-balance {
      font-weight: 600;
      font-size: 14px;

      &.positive-balance {
        color: var(--el-color-success);
      }

      &.zero-balance {
        color: var(--el-text-color-regular);
      }

      &.negative-balance {
        color: var(--el-color-danger);
      }
    }

    .credit-limit {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-top: 2px;
    }
  }

  .text-placeholder {
    color: var(--el-text-color-placeholder);
  }
}
</style>
